package com.ruoyi.door.controller.admin.dept;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.resource.ResourceUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.excel.ExcelUtils;
import com.ruoyi.door.controller.admin.dept.vo.DoorDeptImportVO;
import com.ruoyi.door.service.DoorDeptService;
import com.ruoyi.system.mapper.SysDeptMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 部门管理Controller
 */
@Api(value = "admin 部门管理", tags = "admin 部门管理")
@RestController
@RequestMapping("/admin-api/door/dept")
public class DoorDeptController extends BaseController {

    @Autowired
    private DoorDeptService doorDeptService;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    /**
     * 获取部门导入模板
     */
    @PostMapping("/importTemplate")
    @ApiOperation("部门导入模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        String fileName = "部门导入模板" + DateUtils.getTime() + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        InputStream stream = ResourceUtil.getStream("classpath:" + "template/部门导入模板.xlsx");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);
        ServletOutputStream out = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = stream.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
        out.flush();
        out.close();
    }

    /**
     * 导入部门数据
     */
    @PostMapping("/importData")
    @ApiOperation("部门数据导入")
    @Log(title = "部门管理", businessType = BusinessType.IMPORT)
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        try {
            Map<String, JSONArray> map = ExcelUtils.readFileManySheet(file);

            // 处理部门数据（sheet1）
            JSONArray deptArray = map.get("Sheet1");
            if (deptArray == null || deptArray.isEmpty()) {
                return AjaxResult.error("部门数据sheet为空");
            }

            // 转换为导入VO对象
            List<DoorDeptImportVO> importList = new ArrayList<>();
            for (int i = 0; i < deptArray.size(); i++) {
                JSONObject row = deptArray.getJSONObject(i);
                DoorDeptImportVO vo = new DoorDeptImportVO();

                vo.setCountryName(row.getString("国家"));
                vo.setProvinceName(row.getString("省份"));
                vo.setCityName(row.getString("城市"));
                vo.setDistrictName(row.getString("区/县"));
                vo.setStreetName(row.getString("街道/镇"));
                vo.setVillageName(row.getString("村/社区"));
                vo.setRemark(row.getString("备注"));

                importList.add(vo);
            }

            // 调用服务导入数据
            String message = doorDeptService.importData(importList, updateSupport);
            return AjaxResult.success(message);
        } catch (Exception e) {
            return AjaxResult.error("导入部门数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取部门树形结构
     */
    @GetMapping("/treeselect")
    @ApiOperation("获取部门树形结构")
    public AjaxResult treeselect() {
        List<SysDept> depts = sysDeptMapper.selectDeptList(new SysDept());
        return AjaxResult.success(depts);
    }
}
